package com.zmx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.zmx.entity.SysUser;
import com.zmx.entity.SysUserExt;
import com.zmx.mapper.SysRoleMapper;
import com.zmx.mapper.SysUserMapper;
import com.zmx.service.SysUserService;
import com.zmx.utils.RUtils;
import org.apache.ibatis.annotations.Insert;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 2020/10/19
 * 18:10
 * zmx
 */
@Service("SysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysRoleMapper sysRoleMapper;
    @Override
    public SysUser SysUserLogin(String username) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<SysUser>().eq("username", "admin");
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        return sysUser;
    }

    @Override
    public RUtils findUserPage(int limit, int offset, String search, String order) {
        long total = sysUserMapper.getTotal();
        List<SysUserExt> rows = sysUserMapper.findALl();
        return RUtils.success("查询成功",null).put("total",total)
                .put("rows",rows);
    }

    @Override
    public RUtils saveUser(SysUserExt sysUserExt) {
        String password = new Md5Hash(sysUserExt.getPassword(), "chichi", 1024).toString();
        sysUserExt.setPassword(password);
        SysUser principal = (SysUser) SecurityUtils.getSubject().getPrincipal();
        sysUserExt.setCreateUserId(principal.getUserId());
        sysUserExt.setCreateTime(new Date());
        sysUserMapper.insertUser(sysUserExt);
        sysRoleMapper.insertRoleUser(sysUserExt.getUserId(), sysUserExt.getRoleId());
        return RUtils.success("插入成功",null);
    }

    @Override
    public RUtils selectByUserId(long id) {
        return RUtils.success("查询成功",null).put("menu",sysUserMapper.selectById(id));
    }

    @Override
    public RUtils delete(List<Long> ids) {
        sysUserMapper.deleteBatchIds(ids);
        return RUtils.success("删除成功",null);
    }

    @Override
    public RUtils updateUser(SysUserExt sysUserExt) {
        SysUser sysUser = sysUserExt;
        sysUserMapper.updateById(sysUser);
        return RUtils.success("更新成功",null);
    }
}
